//
//  AppDelegate.m
//  Moonlight
//
//  Created by Diego Waxemberg on 1/17/14.
//  Copyright (c) 2014 Moonlight Stream. All rights reserved.
//

#import "AppDelegate.h"
#import "Moonlight-Swift.h"
#import <SVProgressHUD/SVProgressHUD.h>
//#import <WXApi.h>
//#import <AlipaySDK/AlipaySDK.h>

@interface AppDelegate ()

@end

@implementation AppDelegate

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

static NSOperationQueue* mainQueue;
static NSString* DB_NAME = @"Limelight_iOS.sqlite";

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [AppHelper startEnterApp:self.window];
    
    UIApplicationShortcutItem* shortcut = [launchOptions valueForKey:UIApplicationLaunchOptionsShortcutItemKey];
    if (shortcut != nil) {
        _pcUuidToLoad = (NSString*)[shortcut.userInfo objectForKey:@"UUID"];
    }
    [self func_setupPublicHUD];
    
    // 微信支付SDK初始化
//    [WXApi registerApp:@"wxf386e392b6b1f61a" universalLink:@"wxf386e392b6b1f61a"];
    
    // 支付宝SDK初始化
//    [[AlipaySDK defaultService] setUrl:@"xboxSchemeForAliPay"];

    /* Demo展示直接使用宏PNSATAUTHSDKINFO进行赋值 */
    //测试： Uhrr4tRl6Fz/p/q+g65/PnM9PcslHjfqeF8QHmMUt/ko2fSgIfvftrCEk/F7xkowxGbXPnHwG/2I0c/PzV3caxEeirfz98AhyGm0lWhLqsYCQuBd2sc17Re6YykHKPb3J8a4qWmVNIUlMzc8o/hPd1SgjzSS6ESK5tbBpHmLHQ45Am6fjd4TvqH4R6xIvJOSvqYOUIAKj6MSvXx28XFIGHDZhvcB+2hV9q+0HY6fmjk2f/hDT2uKhPihCJAP8CGeQLRhB4Hbgbc=

    //正式： CQw/tor0jCrMGKqK8ctUnUsVEypjPEVdPxSu71+XLvh2MmGP3QEt00QU0gcNsgmuz0lbBKHTo0eE8rN/3Jj6XNy10b8kFW/nArgj8YpuC8Z3NFc+r0SEh5IicZJhAScrVh0uNzDJw1z31MIPJg7MQmZi9wpjvYg9SS0+2dhq4wB2VZWVcXWw+Y2GIlDvxWYbe0ptGxw/88mNvi72xRrOU/9/lDFk238h8p6igvIOm3LdlVvtPUCcgK5GcO/KE0eQ

    // 主包：yWRFU1puYopY2EDcvJOizx+j6Y6BYoGfIYjSIgU/gK65t8YSH1vBJiCflCwJzEIyadncjh7ppz2B1Ze1piQl3mQaw8Rvq+v0RzCpMXzgQz5Wmul1Ph3GhA/TS6b6bSIsDc3Rx3e2A1DxQfEmrgOaXWBxaU0KpE5P9VpvV2jRaLNNo4WFOTMQLSLY3yAsfiwE/T6dlg5tbSVktpG0ddwzv9F669ZQUKaiKQe1bO4eL5MLJVOHCnvY632rAAu6EKY3RoSzLhx77Ss=

    [[TXCommonHandler sharedInstance] setAuthSDKInfo:@"yWRFU1puYopY2EDcvJOizx+j6Y6BYoGfIYjSIgU/gK65t8YSH1vBJiCflCwJzEIyadncjh7ppz2B1Ze1piQl3mQaw8Rvq+v0RzCpMXzgQz5Wmul1Ph3GhA/TS6b6bSIsDc3Rx3e2A1DxQfEmrgOaXWBxaU0KpE5P9VpvV2jRaLNNo4WFOTMQLSLY3yAsfiwE/T6dlg5tbSVktpG0ddwzv9F669ZQUKaiKQe1bO4eL5MLJVOHCnvY632rAAu6EKY3RoSzLhx77Ss=" complete:^(NSDictionary * _Nonnull resultDic) {
        NSLog(@"设置秘钥结果：%@", resultDic);
    }];

    return YES;
}

//MARK: - 设置HUD
- (void)func_setupPublicHUD {
    [SVProgressHUD setBackgroundColor:[UIColor.blackColor colorWithAlphaComponent:0.9f]];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    [SVProgressHUD setBackgroundLayerColor:[UIColor clearColor]];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setDefaultAnimationType:(SVProgressHUDAnimationTypeNative)];
    [SVProgressHUD setForegroundColor:UIColor.whiteColor];
    [SVProgressHUD setRingThickness:2];
    [SVProgressHUD setRingRadius:20];
    [SVProgressHUD setMinimumSize:CGSizeMake(90, 90)];
    [SVProgressHUD setFont:[UIFont systemFontOfSize:13]];
    [SVProgressHUD setMaximumDismissTimeInterval:2.0f];
    [SVProgressHUD setMinimumDismissTimeInterval:1.0f];
}

- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL succeeded))completionHandler {
    _pcUuidToLoad = (NSString*)[shortcutItem.userInfo objectForKey:@"UUID"];
    _shortcutCompletionHandler = completionHandler;
}

- (void)applicationWillTerminate:(UIApplication *)application {
    [self saveContext];
}

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
    if (managedObjectContext != nil) {
        [managedObjectContext performBlock:^{
            if (![managedObjectContext hasChanges]) {
                return;
            }
            NSError *error = nil;
            if (![managedObjectContext save:&error]) {
                Log(LOG_E, @"Critical database error: %@, %@", error, [error userInfo]);
            }
        }];
    }
}

#pragma mark - Core Data stack

// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext {
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel {
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    _managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
    return _managedObjectModel;
}

// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                             [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
    NSString* storeType = NSSQLiteStoreType;

    
    // We must ensure the persistent store is ready to opened
    [self preparePersistentStore];
    
    if (![_persistentStoreCoordinator addPersistentStoreWithType:storeType configuration:nil URL:[self getStoreURL] options:options error:&error]) {
        // Log the error
        Log(LOG_E, @"Critical database error: %@, %@", error, [error userInfo]);
        
        // Drop the database
        [self dropDatabase];
        
        // Try again
        return [self persistentStoreCoordinator];
    }
    
    return _persistentStoreCoordinator;
}

#pragma mark - Application's Documents directory

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory {
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (void) dropDatabase {
    // Delete the file on disk
    [[NSFileManager defaultManager] removeItemAtURL:[self getStoreURL] error:nil];
}

- (void)preparePersistentStore {

}

- (NSURL*)getStoreURL {
    return [[self applicationDocumentsDirectory] URLByAppendingPathComponent:DB_NAME];
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
//- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
//    // 支付宝支付回调
//     [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//         [self handleAliPayResult:resultDic];
//     }];
//
//    // 微信支付回调
//    BOOL wxPayHandled = [WXApi handleOpenURL:url delegate:self];
//    // 如果需要处理其他URL Scheme，请在此处添加相应的处理逻辑
//    return wxPayHandled;
//}
#pragma clang diagnostic pop

//- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
//    // 支付宝支付回调
//    [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//        [self handleAliPayResult:resultDic];
//    }];
//
//    // 微信支付回调
//    BOOL wxPayHandled = [WXApi handleOpenURL:url delegate:self];
//
//    // 如果需要处理其他URL Scheme，请在此处添加相应的处理逻辑
//    return wxPayHandled;
//}

- (void)handleAliPayResult:(NSDictionary *)resultDic {
    // 处理支付宝支付结果
    NSInteger resultStatus = [resultDic[@"resultStatus"] integerValue];
    if (resultStatus == 9000) {
        // 支付成功
        [[NSNotificationCenter defaultCenter] postNotificationName:@"DID_PAYSUCCESS_NOTIFICATION" object:nil];
    } else {
        // 支付失败
        [[NSNotificationCenter defaultCenter] postNotificationName:@"DID_PAYERROR_NOTIFICATION" object:nil];
    }
}

#pragma mark - WXApiDelegate

//- (void)onResp:(BaseResp *)resp {
//    if ([resp isKindOfClass:[PayResp class]]) {
//        PayResp *payResp = (PayResp *)resp;
//
//        // 处理微信支付结果
//        if (payResp.errCode == WXSuccess) {
//            // 支付成功
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"DID_PAYSUCCESS_NOTIFICATION" object:nil];
//        } else {
//            // 支付失败
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"DID_PAYERROR_NOTIFICATION" object:nil];
//        }
//    }
//}

/**
 * 屏幕转向
 */
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window {
    if (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad) {
        // 设备是iPad
        return UIInterfaceOrientationMaskLandscapeRight;
    } else {
        // 设备不是iPad
        if (_allowRotation == YES) {
            return UIInterfaceOrientationMaskLandscapeRight;
        }else{
            return (UIInterfaceOrientationMaskPortrait);
        }
    }
}

@end
